package io.babystar.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.babystar.common.utils.DateUtils;
import io.babystar.modules.sys.dao.SysSMSCodeDao;
import io.babystar.modules.sys.entity.SysSMSCodeEntity;
import io.babystar.modules.sys.service.SysSMSCodeService;
import org.springframework.stereotype.Service;
import java.util.Date;

/**
 * 验证码
 *
 * @author Mark whc
 */
@Service("sysSMSCodeService")
public class SysSMSCodeServiceImpl extends ServiceImpl<SysSMSCodeDao, SysSMSCodeEntity> implements SysSMSCodeService {

    @Override
    public void saveSMSCode(String phone, String code) {
        SysSMSCodeEntity smsCodeEntity = new SysSMSCodeEntity();
        smsCodeEntity.setPhone(phone);
        smsCodeEntity.setCode(code);

        //5分钟后过期
        smsCodeEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
        this.saveOrUpdate(smsCodeEntity);
    }

    @Override
    public boolean validate(String phone, String code) {
        SysSMSCodeEntity captchaEntity = this.getOne(new QueryWrapper<SysSMSCodeEntity>().eq("phone", phone));
        if(captchaEntity == null){
            return false;
        }
        //删除验证码
        this.removeById(phone);

        if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
            return true;
        }

        return false;
    }
}
